<template>
  <main>
    <h1>This is an home page</h1>
    <p>响应式 ref 用法</p>
    <div>count: {{ count }}</div>
    <button @click="count++">increment count!</button>
    <div>
      计算属性:
      {{ state.todoList }} 是否完成todoList ?
      {{ finished }}
    </div>
    <div>
      计算属性 依赖非响应式对象将不会更新
      {{ now }}
    </div>
    <div>
      <p class="bakground" :class="{ active: state.isActive, text }">
        类与样式绑定(多个class样式合并)
      </p>
      <p>组件中使用样式绑定</p>
      <MyComponent :class="{ active: state.isActive }" :size="state.size" @changeSize="(val) => console.log(val)" />
    </div>
    <div>
      <p>事件处理</p>
      <button @click="greet">greet it</button>
    </div>
    <div>
      <p>侦听器</p>
      <input v-model="question" />
      <p>{{ answer }}</p>
    </div>
    <div>
      <p>模板引用 ref</p>
      <input ref="input">
    </div>
  </main>
</template>

<script>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import MyComponent from '@/components/MyComponent.vue'
export default {
  setup() {
    /**
     * 声明 响应式状态（深层响应）
     * ref 响应式任何值
     * reactive 响应式对象
     */
    const count = ref(1);
    const text = ref(true);
    const question = ref('')
    const answer = ref('')
    const input = ref(null)

    const state = reactive({
      count,
      todoList: [1, 2, 3],
      isActive: true,
      // text: true,
      size: '14px',
      // changeSize
    });

    // console.log('ref的自动解包', state.count);
    // console.log('ref访问 .value', count.value);

    /**
     * 计算属性ref
     * compute(getter())
     */
    const finished = computed(() => {
      return state.todoList.length ? 'no' : 'yes';
    });
    const changeSize = (val) => {
      console.log('changeSize!')
      state.size = val;
    }

    const now = computed(() => Date.now());
    const greet = (event) => {
      alert('hello');
      console.log(event.target)
    }
    // 侦听ref
    watch(question, (val) => {
      if (val.includes('?')) {
        answer.value = 'yes';
      } else {
        answer.value = 'thinking...';
      }
    })
    //侦听 reactive
    watch(
      () => state.count,
      (val) => {
        console.log('watch reactive val,count is', state.count)
      },
      { immediate: true }
    )
    onMounted(() => {
      console.log('onMounted')
      input.value.focus()
    })
    //在 setup() 函数中手动暴露大量的状态和方法非常繁琐。
    return {
      // ref 模板中自动解包
      count,
      state,
      finished,
      now,
      text,
      greet,
      question,
      answer,
      input,
    };
  },
  components: { MyComponent }
}
</script>
<style scoped>
.active {
  color: red;
}

.text {
  font-size: 30px;
}

.bakground {
  background-color: yellowgreen;
}
</style>
